package com.wh.base.sys.other.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.base.aop.documented.OperLog;
import com.wh.base.sys.cert.entity.Cert;
import com.wh.base.sys.other.controller.form.*;
import com.wh.base.sys.other.entity.Other;
import com.wh.base.sys.other.service.OtherService;
import com.wh.base.sys.user.service.UserService;
import com.wh.base.util.ExcelUtil;
import com.wh.base.util.R;
import com.wh.base.util.RedisUtil;
import com.wh.base.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author Pny
 * @Date 2022/5/20
 */
@Controller
@RequestMapping("/sys/other")
public class OtherController {

    @Autowired
    private OtherService otherService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @Resource
    private ExcelUtil excelUtil;


    @GetMapping("/index")
    @ApiOperation(value = "首页页面")
    @SaCheckPermission("other:view")
    public String index(Model model){
        model.addAttribute("authSign", (Map<String,String>)redisUtil.get("auth_sign_"+ StpUtil.getLoginIdAsLong())); //用户权限
        return "other/index";
    }

    @PostMapping("/getPage")
    @ApiOperation(value = "分页查询数据")
    @ResponseBody
    @SaCheckLogin
    public R getPage(@Validated SearchPageForm form){

        LambdaQueryWrapper<Other> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtil.isEmpty(form.getName())){
            queryWrapper.like(Other::getName,form.getName());
        }
        if (!StringUtil.isEmpty(form.getCardNumber())){
            queryWrapper.like(Other::getCardNumber,form.getCardNumber());
        }
        if (!StringUtil.isEmpty(form.getStudentNumber())){
            queryWrapper.like(Other::getStudentNumber,form.getStudentNumber());
        }
        if (!StringUtil.isEmpty(form.getCertName())){
            queryWrapper.like(Other::getCertName,form.getCertName());
        }
        if (!StringUtil.isEmpty(form.getCertSerial())){
            queryWrapper.like(Other::getCertSerial,form.getCertSerial());
        }
        if (!StringUtil.isEmpty(form.getCertType())){
            queryWrapper.like(Other::getCertType,form.getCertType());
        }
        if (!StringUtil.isEmpty(form.getLicenceIssued())){
            queryWrapper.like(Other::getLicenceIssued,form.getLicenceIssued());
        }

        Page roadPage = new Page<>(form.getPageNum(), form.getPageSize());
        queryWrapper.eq(Other::getIsDelete,0);
        Page pageList = otherService.page(roadPage, queryWrapper);
        return R.ok().put("page", pageList);
    }


    @OperLog(operModul = "其他证书管理",operType = "添加",operDesc = "添加其他证书")
    @ResponseBody
    @PostMapping("/add")
    @SaCheckPermission("other:add")
    public R add(Other other){
        System.out.println("进入otheradd----------");
        boolean save = otherService.save(other);
        if (save == false){
            return R.error();
        }else
            return R.ok();
    }

    @OperLog(operModul = "其他证书管理",operType = "删除",operDesc = "删除其他证书")
    @ResponseBody
    @GetMapping("/delete/{id}")
    @SaCheckPermission("other:delete")
    public R delete(@PathVariable int id){
        otherService.removeById(id);
        return R.ok();
    }


    @ResponseBody
    @GetMapping("/load/{id}")
    @SaCheckPermission("other:load")
    public R load(@PathVariable int id){
        Other other = otherService.getById(id);
        return R.ok().put("data",other);

    }

    @OperLog(operModul = "其他证书管理",operType = "修改",operDesc = "修改其他证书")
    @ResponseBody
    @PostMapping("/update")
    @SaCheckPermission("other:update")
    public R update(Other other){
        boolean b = otherService.updateById(other);
        if (b == false){
            return R.error();
        }else
            return R.ok();

    }

    @GetMapping("/recycleIndex")
    @ApiOperation(value = "回收站页面")
    public String recycleIndex(Model model){
        model.addAttribute("authSign", (Map<String,String>)redisUtil.get("auth_sign_"+StpUtil.getLoginIdAsLong())); //用户权限
        return "other/recycle";
    }

    @PostMapping("/recycle")
    @ApiOperation(value = "根据id集合将数据放入回收站")
    @ResponseBody
    @OperLog(operModul = "其他证书管理", operType = "放入回收站" ,operDesc = "将其他证书放入回收站")
    public R recycle(@Validated IdsForm form){
        List<Long> idList = form.idList();
        if(idList.size() > 0) {
            List<Other> otherList = new ArrayList<>();
            for(Long id : idList) {
                Other other = new Other();
                other.setId(id);
                other.setIsDelete(1);
                other.setUpdateTime(new Date());
                other.setUpdateUser(userService.getUser().getUsername());
                otherList.add(other);
            }
            if(otherList.size() > 0) {
                otherService.saveOrUpdateBatch(otherList);
            }
        }
        return R.ok("删除成功");
    }

    @OperLog(operModul = "其他证书管理",operType = "恢复其他证书",operDesc = "还原回收站的其他证书")
    @PostMapping("/restore")
    @ApiOperation(value = "根据ids批量还原回收站的数据")
    @ResponseBody
    public R restore(@Validated IdsForm form){
        List<Long> idList = form.idList();
        if(idList.size() > 0) {
            List<Other> otherList = new ArrayList<>();
            for(Long id : idList) {
                Other other = new Other();
                other.setId(id);
                other.setUpdateTime(new Date());
                other.setIsDelete(0);
                otherList.add(other);
            }
            if(otherList.size() > 0) {
                otherService.saveOrUpdateBatch(otherList);
            }
        }
        return R.ok("还原成功");
    }

    @PostMapping("/getRecyclePage")
    @ApiOperation(value = "分页查询回收站数据")
    @ResponseBody
    public R getRecyclePage(@Validated SearchPageForm form){
        Page roadPage = new Page<>(form.getPageNum(), form.getPageSize());
        LambdaQueryWrapper<Other> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(Other::getIsDelete, 1);

        Page pageList = otherService.page(roadPage, queryWrapper);
        return R.ok().put("page", pageList);
    }



    @PostMapping("/delete")
    @ApiOperation(value = "根据id集合彻底删除数据")
    @SaCheckPermission("other:delete")
    @ResponseBody
    @OperLog(operModul = "其他管理", operType = "彻底删除" ,operDesc = "彻底删除其他证书")
    public R delete(@Validated IdsForm form){
        List<Long> idList = form.idList();
        //检查是否存在不能修改的数据

        if(idList.size() > 0) {
            otherService.removeByIds(idList);
        }
        return R.ok("删除成功");
    }


    //    导入Excel
    @PostMapping ("/excel")
    @ResponseBody
    @SaCheckLogin
    @OperLog(operModul = "其他证书上传Excel",operType = "批量上传",operDesc = "批量上传其他证书")
    public R importExcel(@RequestPart MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        List<List<Object>> bankListByExcel = excelUtil.getBankListByExcel(inputStream, filename);
        List<Object> objects = null;

        Other other = null;
        for (int i = 0; i < bankListByExcel.size(); i++) {
            objects = bankListByExcel.get(i);
            other = new Other();
            for (int j = 0; j < objects.size(); j++) {

                String o = (String)objects.get(j);
                if (j ==0){
                    other.setName(o);
                }
                if (j == 1){
                    if (o.contains(".")){
                        String str = o.substring(0,o.indexOf("."));
                        other.setCardNumber(str);
                    }
                    other.setCardNumber(o);
                }
                if (j == 2){
                    if (o.contains(".")){
                        String substring = o.substring(0, o.indexOf("."));
                        other.setStudentNumber(substring);
                    }
                    other.setStudentNumber(o);
                }
                if (j == 3){
                    other.setCertName(o);
                }
                if (j == 4){
                    other.setCertSerial(o);
                }
                if (j == 5){
                    other.setCertType(o);
                }
                if (j == 6){

                    other.setLicenceIssued(new SimpleDateFormat("yyyy-MM-dd").parse(o));
                }

            }

            other.setCreateTime(new Date());
            other.setCreateUser(userService.getUser().getUsername());
            otherService.save(other);
        }

        return R.ok("批量导入成功！");
    }


}
